<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 <style type="text/css">
	     .selectkpiClass{
		       height:23px;
		       line-height:21px;
			   width:270px;
			   border:#cbcbcb solid 1px;
	     }
    </style>
<link href="${pageContext.request.contextPath}/js/uploadify/uploadify.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/uploadify/jquery.uploadify.js"></script>  
<script type="text/javascript">
var validkqiid = null ;
var validkqiversion = null;
var successline = null;
var failline = null;
var importtype = null;
var uploadfilepath = null;
var realkqiname = null;
	$(function() {

		 $(".listtable").zebra(); 
		//默认隐藏上传文件
		$("#file_upload_showorhidden").hide();
		
		 $('#dqm_kqiinfo_table').datagrid({
				url:'',
				title:'指标列信息',
				fit:true,
				border:false,
				fitColumns:true,
				pagination:false,
				striped:true,
				rownumbers:false,
				singleSelect:false,
				pagePosition:'bottom',
				autoRowHeight:true,
				columns: [[
						]],
		 toolbar:'#dqm_accuracyruleconf_dimdatagridaddtoolbar'
			});
		//加载指标名称数据
		$('#kqinameQ').combogrid({   
			delay: 500,
			panelWidth:450,
			mode: 'remote',   
			url: '${pageContext.request.contextPath}/mininganalysis/dataImportAction!getAllKqiName.action',   
			idField: 'kqiid',   
			textField: 'kqiname',  
	        pagination : true,//是否分页  
	        rownumbers:true,//序号  
	        collapsible:false,//是否可折叠的  
	        fit: true,//自动大小  
	        fitColumns:true,
	        pageList:[10,20,30],//可以设置每页记录条数的列表  
	        method:'post', 
			columns: [[   
			      {field:'kqiid',title:'指标ID',width:50,sortable:true,align:'center'},   
			      {field:'kqiname',title:'指标名称',width:85,align:'center'},
			      {field:'kqiversionnum',title:'版本号',width:85,align:'center'} 
			]],
			toolbar:'#tb',
			
			onSelect:function(value,rowData,rowIndex){
				validkqiid = rowData.kqiid;	
				validkqiversion = rowData.kqiversionnum;
				$("#dataimport_kqiversionnum").val(rowData.kqiversionnum);
				$("#dataimport_kqiid").val(rowData.kqiid);
				$("#dataimport_kqiname").val(rowData.kqiname);
				document.getElementById("dataimport_kqiid_tmp").innerText=rowData.kqiid;				
				$("#file_upload_showorhidden").hide();
				$('#file_upload').uploadify({
				    'formData':{"kqiid":rowData.kqiid},
				    'fileTypeDesc' : '只支持以下几种文件格式',
			        'fileTypeExts' : '*.dat; *.txt;',
					'cancelImg': '${pageContext.request.contextPath}/js/uploadify/uploadify-cancel.png', 
					'swf'    : '${pageContext.request.contextPath}/js/uploadify/uploadify.swf',
					'uploader' : '${pageContext.request.contextPath}/mininganalysis/dataImportAction!uploadData.action?kqiname='+$("#dataimport_kqiid_tmp").val()+'&kqiversionnum='+$("#dataimport_kqiversionnum").val(),
					'multi':false,
					'buttonText':'',
				     'width' : 88,   
				     'height':27,
				     'auto':true,
					 'onUploadSuccess' : function(file, data, response) {
						 	var msg = $.parseJSON(data);
				            window.top.$.messager.alert('提示',msg.returnMsg);
							uploadfilepath = msg.obj.filepath;
	 	   		    	    $("#dataimport_filepath").val(uploadfilepath);
	 	   				    var dgtables=$('#dqm_kqiinfo_table').datagrid('options');
	 	   				    
	 	   				    dgtables.url='${pageContext.request.contextPath}/mininganalysis/dataImportAction!fetchFileRows.action?filepath='+uploadfilepath;
	 					    //重新配置datagrid
	 					    $('#dqm_kqiinfo_table').datagrid(dgtables); 
	 					   //	$('#dqm_kqiinfo_table').datagrid('reload');	 					    	 					  	 					
	 					    $("#dqm_accuracyruleconf_dimdatagridaddtoolbar").hide();
	 					   //$("#file_upload_showorhidden").hide();
				        }
				}); 
				
				 var dgOptions=$('#dqm_kqiinfo_table').datagrid('options');
				 dgOptions.columns[0]=[];

				 $.ajax({
					 url:'${pageContext.request.contextPath}/mininganalysis/dataImportAction!getKqiColInfo.action',
					 data:{"kqiid":rowData.kqiid,"kqiversionnum":rowData.kqiversionnum},
					 dataType :'json',
					 cache : true,
					 success : function(dyColumns){ 
						// console.info(dyColumns);
						 if(null!=dyColumns){
								//获取datagrid的配置信息
								var dgOptions=$('#dqm_kqiinfo_table').datagrid('options');
								//dyColumns类似:[{field:'dim_city',title:'南京'}，{field:'dim_city',title:'南京'}]
								for(var idx=0;idx<dyColumns.length;idx++){
									//往json对象中添加属性，变成类似:{field:'dim_city',title:'南京',width:80,align:'center',editor:'text'}
									dyColumns[idx].editor={
											type:'validatebox',
											options:
											{
												required:true
											}};
									dyColumns[idx].width=30;
									dyColumns[idx].height=60;
									dyColumns[idx].align="center";
									//向datagrid的第一个列列数组的最前面添加列
									dgOptions.columns[0].push(dyColumns[idx]);
								}
								//重新配置datagrid
								$('#dqm_kqiinfo_table').datagrid(dgOptions); 
								//重新加载datagrid
								//$('#dqm_kqiinfo_table').datagrid('reload');
						 }
					 }
					 
			     });
				
		    }
		});  

	});		
	//切换是否显示文件上传
	function fileShowOrHide(){
		var temp=$("#upLoadSelectId").val();
		if(temp==0){
			$("#file_upload_showorhidden").toggle(true);
			$("#dqm_accuracyruleconf_dimdatagridaddtoolbar").toggle(false);
		}else{
			$("#file_upload_showorhidden").toggle(false);
			$("#dqm_accuracyruleconf_dimdatagridaddtoolbar").toggle(true);
		}
	}
	
	function queryUser()
	{
		var kqiname=$('#query_userName').val();	
		var query={kqiname:kqiname}; //把查询条件拼接成JSON
		var grid=$("#kqinameQ").combogrid('grid');
		$(grid).datagrid('options').queryParams=query; //把查询条件赋值给datagrid内部变量
		$(grid).datagrid('load');
	}
	
	function resetQuery()
  	{
		$('#query_userName').val('');
   	}
	
	

	var editIndex = undefined;
	function endEditing(){
		if (editIndex == undefined){return true}
		if ($('#dqm_kqiinfo_table').datagrid('validateRow', editIndex)){	
			$('#dqm_kqiinfo_table').datagrid('endEdit', editIndex);
			editIndex = undefined;
			return true;
		} else {
			return false;
		}
	}

	function append(){
		if (endEditing()){
			$('#dqm_kqiinfo_table').datagrid('appendRow',{});
			editIndex = $('#dqm_kqiinfo_table').datagrid('getRows').length-1;
			$('#dqm_kqiinfo_table').datagrid('selectRow', editIndex).datagrid('beginEdit', editIndex);
		}
		//$('#dqm_kqiinfo_table').datagrid('reload');
	}
	function remove(){
		if (editIndex == undefined){return}
		$('#dqm_kqiinfo_table').datagrid('cancelEdit', editIndex).datagrid('deleteRow', editIndex);
		editIndex = undefined;
	}
	function accept(){
		if (endEditing()){
			$('#dqm_kqiinfo_table').datagrid('acceptChanges'); 
		}
	}
	function reject(){
		$('#dqm_kqiinfo_table').datagrid('rejectChanges');
		editIndex = undefined;
	}
	
	function commit()
	{
		if(endEditing())
		{
			saveData();
		}
	}
	
	
	//保存手工导入的数据
	function saveData()
	{
		if($('#dqm_kqiinfo_table').datagrid('getChanges').length)
		{
			//获取datagrid的配置信息
			var allColumns=$('#dqm_kqiinfo_table').datagrid('options').columns[0];
			var columns = new Array();
			for(var i=0;i<allColumns.length;i++)
			{//第0行恰好是不定个数的维度字段，相当于是批量导入中约定的文件第一行
					columns.push(allColumns[i]);
				
			}
			var inserted=$('#dqm_kqiinfo_table').datagrid('getChanges',"inserted");
			var deleted=$('#dqm_kqiinfo_table').datagrid('getChanges',"deleted");
			var updated=$('#dqm_kqiinfo_table').datagrid('getChanges',"updated");
			var effectRow = new Object();
			if(inserted.length){
				effectRow["inserted"] = JSON.stringify(inserted);
			}
			if(deleted.length){
				effectRow["deleted"] = JSON.stringify(deleted); 
			}
			if(updated.length){
				effectRow["updated"] = JSON.stringify(updated);
			}
			
			effectRow["columns"]=JSON.stringify(columns);			
			effectRow["validkqiid"]=JSON.stringify(validkqiid);
			effectRow["validkqiversion"]=JSON.stringify(validkqiversion);
			
			importtype =$("#upLoadSelectId").val();
			realkqiname=$("#dataimport_kqiname").val();
			
			var pars="kqiname="+validkqiid+"&creator="+validkqiversion+"&dataimporttype="+importtype+"&remark="+realkqiname;
			$.messager.progress({
				title : '提示',
				text : '数据提交中，请稍后 ....'
			});
			$.post(
					"${pageContext.request.contextPath}/mininganalysis/dataImportAction!saveData.action?"+pars,
					effectRow,
					function(rsp){
						try {
							if (rsp.returnFlag) {
								$.messager.alert("提示", rsp.returnMsg);
								successline = rsp.obj.successline;
								failline = rsp.obj.failline;
		 	       		    	$("#dataimport_successline").val(successline);
		 	   		    	    $("#dataimport_failline").val(failline);
								$('#dqm_kqiinfo_table').datagrid('acceptChanges');
								reject();
							}
							else {
								$.messager.alert("提示", rsp.returnMsg); 
								successline = rsp.obj.successline;
								failline = rsp.obj.failline;
		 	       		    	$("#dataimport_successline").val(successline);
		 	   		    	    $("#dataimport_failline").val(failline);
							}
							$.messager.progress('close');
						} catch (e) {
							$.messager.progress('close');
						}
					},
					"json"
				);
		}
	}	
	
	function batchImport()
	{
		validkqiid = $("#dataimport_kqiid").val();
		validkqiversion = $("#dataimport_kqiversionnum").val();
		importtype =$("#upLoadSelectId").val();
		realkqiname = $("#dataimport_kqiname").val();
		uploadfilepath = $("#dataimport_filepath").val();
		if(uploadfilepath==null||uploadfilepath==undefined||uploadfilepath=='')
		{
			$.messager.alert("提示", '请先上传文件');
			return;
		}
		var pars="kqiname="+validkqiid+"&creator="+validkqiversion+"&dataimporttype="+importtype+"&filepath="+uploadfilepath;
		$.messager.progress({title : '提示',text : '提交数据中，请稍后 ....'});
		$.post(
				"${pageContext.request.contextPath}/mininganalysis/dataImportAction!batchImport.action?"+pars,
				 function(rsp){
					try {
						if (rsp.returnFlag) {
							$.messager.alert("提示", rsp.returnMsg);

						}
						else {
							$.messager.alert("提示", rsp.returnMsg); 

						}
						$.messager.progress('close'); 
					} catch (e) {
						$.messager.progress('close'); 
					}
				 },
				 "json"
			);
	}
	
</script>
 <div style="text-align:center"> 
 	<form id="dataImport_main_form" method="post">
	 	<table class="listtable"  border="0" cellpadding="0" cellspacing="0" height="40px"  width="100%">
	 	   <tr>
	 	     <td height="30px" style="text-align:right;"><span style="color:red;font-size:15px">*</span>指标名称：&nbsp;</td>
	 	     <td text-align:left;height:30px;">
	 	       <input type="hidden" id="dataimport_kqiid" name="kqiid" />
	 	       <input type="hidden" id="dataimport_kqiname" name="kqiname" />
	 	       <input type="hidden" id="dataimport_kqiversionnum" name="kqiversionnum" />
	 	       <input type="hidden" id="dataimport_successline" name="successline" />
	 	       <input type="hidden" id="dataimport_failline" name="failline" />
	 	       <input type="hidden" id="dataimport_filepath" name="filepath" />
	 	       <input type="text" id="kqinameQ" name=""  data-options="required:true,missingMessage:'指标名称不能为空'" style="width:200px;"/>
	 	     </td>

	 	     <td height="30px" style="text-align:right;">导入方式：&nbsp;</td>
	 	     <td style="text-align:left;height:30px">
	 	       <select id="upLoadSelectId" name="dataimporttype" class="selectkpiClass" style="width:200px" onchange="fileShowOrHide()">
	 	          <option value="1">手工录入</option>
	 	          <option value="0">批量导入</option>

	 	       </select>
	 	     </td>
	 	   </tr>

	    </table>
	    </form>
	    <div id="file_upload_showorhidden">
 <form class="uploadifyDiv">

			<div id="queue"></div> 
			<tr>
			<td><input id="file_upload" name="filedata"  type="file" multiple="true"></td>
				<td><div class="uploadifyDesc"><span style="color:red;font-size:15px">*</span>上传附件格式为：.txt、.dat，文件大小不大于100M，最多导入1个文件</div></td>
				<!-- 用于显示进度条 -->
				<div id="uploadfileQueue_add"></div>  
			</tr>			
			<td style="width:70%;text-align:right;height:30px;"><input type="hidden" id="dataimport_kqiid_tmp" name="kqiid" /></td>
			<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true" onclick="batchImport()">提交数据</a>

</form>
</div>

	 <div data-options="region:'center'" style="border-top-color:#cbcbcb;border-top:none">  
		<table id="dqm_kqiinfo_table"></table><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
		  <div id="dqm_accuracyruleconf_dimdatagridaddtoolbar">
			<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:true" onclick="append()">添加</a>
			<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-undo',plain:true" onclick="reject()">撤销 </a>
			<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok',plain:true" onclick="commit()">提交</a>
		  </div>
		  		
	 </div>
	

  
 </div>
 <div id="tb" style="padding:5px;height:auto">   
    <div>  
               指标名称：<input id="query_userName" type="text" class="easyui-validatebox" style="width:150px" >  
        <input type="button" id="btnQuery" onclick="queryUser()" value="查 询" style="cursor:pointer;background-image: url('${pageContext.request.contextPath}/images/login/search.png');background-repeat: no-repeat;width:67px;height:23px;padding-left:12px;border:none;color:white;font-family:微软雅黑;"/>	
		<input type="button" id="btnReset" onclick="resetQuery()" value="重 置" style="cursor:pointer;background-image: url('${pageContext.request.contextPath}/images/login/reset.png');background-repeat: no-repeat;width:67px;height:23px;padding-left:12px;border:none;color:white;font-family:微软雅黑;margin-right:55px"/> 
    </div>  
</div>